package com.obggtc.picture.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频功能使用示例
 * 展示如何使用视频相关的工具类和接口
 */
@Component
public class VideoExampleUsage {

    @Autowired
    private VideoCacheUtils videoCacheUtils;

    @Autowired
    private RedisLockUtils redisLockUtils;

    @Autowired
    private RedisRateLimiterUtils rateLimiterUtils;

    /**
     * 视频缓存操作示例
     */
    public void videoCacheExample() {
        String videoId = "video_123456";
        String username = "testuser";

        // 1. 缓存视频基本信息
        Map<String, Object> videoInfo = new HashMap<>();
        videoInfo.put("videoId", videoId);
        videoInfo.put("fileName", "demo_video.mp4");
        videoInfo.put("fileSize", "52428800"); // 50MB
        videoInfo.put("fileType", "video/mp4");
        videoInfo.put("uploader", username);
        videoInfo.put("uploadTime", System.currentTimeMillis());
        videoInfo.put("title", "演示视频");
        videoInfo.put("description", "这是一个演示视频");
        videoInfo.put("videoUrl", "http://localhost:8084/static/video/video_123456.mp4");
        
        videoCacheUtils.cacheVideoInfo(videoId, videoInfo);

        // 2. 增加观看次数
        long viewCount = videoCacheUtils.incrementViewCount(videoId);
        System.out.println("当前观看次数: " + viewCount);

        // 3. 添加到用户视频列表
        videoCacheUtils.addUserVideo(username, videoId);

        // 4. 缓存视频标签
        List<String> tags = Arrays.asList("教程", "演示", "技术");
        videoCacheUtils.cacheVideoTags(videoId, tags);

        // 5. 为每个标签添加视频
        for (String tag : tags) {
            videoCacheUtils.addVideoToTag(tag, videoId);
        }

        // 6. 添加到最近上传列表
        videoCacheUtils.addToRecentUploads(videoId);

        // 7. 缓存缩略图信息（如果有的话）
        videoCacheUtils.cacheThumbnailInfo(videoId, "/thumbnails/video_123456_thumb.jpg", 180L); // 3分钟视频

        // 8. 设置视频处理状态
        videoCacheUtils.setProcessingStatus(videoId, "completed", 100);

        // 9. 添加到热门视频（基于观看量计算热度分数）
        double hotScore = viewCount * 1.0 + tags.size() * 0.5;
        videoCacheUtils.addToHotVideos(videoId, hotScore);
    }

    /**
     * 视频分布式锁使用示例
     */
    public void videoLockExample() {
        String filename = "important_video.mp4";
        String videoId = "video_123456";

        // 1. 视频上传锁
        String uploadLock = redisLockUtils.tryVideoUploadLock(filename);
        if (uploadLock != null) {
            try {
                // 执行视频上传逻辑
                System.out.println("正在上传视频: " + filename);
                Thread.sleep(5000); // 模拟上传耗时
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                redisLockUtils.unlock("video:upload:" + filename, uploadLock);
            }
        }

        // 2. 视频处理锁
        String processLock = redisLockUtils.tryVideoProcessLock(videoId);
        if (processLock != null) {
            try {
                // 执行视频处理逻辑（如生成缩略图、转码等）
                System.out.println("正在处理视频: " + videoId);
                Thread.sleep(10000); // 模拟处理耗时
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                redisLockUtils.unlock("video:process:" + videoId, processLock);
            }
        }

        // 3. 使用锁执行业务逻辑（推荐方式）
        try {
            String result = redisLockUtils.executeWithLock("video:process:" + videoId, () -> {
                // 视频处理逻辑
                System.out.println("正在生成视频缩略图: " + videoId);
                return "缩略图生成完成";
            });
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("获取锁失败或处理异常: " + e.getMessage());
        }
    }

    /**
     * 视频限流使用示例
     */
    public void videoRateLimiterExample() {
        String username = "testuser";
        String userIp = "192.168.1.100";

        // 1. 视频上传限流 - 每小时最多上传5个视频
        boolean uploadAllowed = rateLimiterUtils.isVideoUploadAllowed(username, 5, 3600);
        if (!uploadAllowed) {
            System.out.println("视频上传频率过高，请稍后再试");
            return;
        }

        // 2. 视频观看限流 - 每分钟最多观看50个视频
        boolean viewAllowed = rateLimiterUtils.isVideoViewAllowed(userIp, 50, 60);
        if (!viewAllowed) {
            System.out.println("视频观看频率过高，请稍后再试");
            return;
        }

        System.out.println("所有视频限流检查通过，可以处理请求");
    }

    /**
     * 综合使用示例：视频上传场景
     */
    public void videoUploadScenario(String username, String filename) {
        // 1. 视频上传限流检查
        if (!rateLimiterUtils.isVideoUploadAllowed(username, 5, 3600)) {
            throw new RuntimeException("视频上传频率过高，每小时最多上传5个视频，请稍后再试");
        }

        // 2. 获取视频上传锁
        String lockValue = redisLockUtils.tryVideoUploadLock(filename);
        if (lockValue == null) {
            throw new RuntimeException("该视频文件正在被其他用户上传，请稍后再试");
        }

        try {
            // 3. 执行上传逻辑
            String videoId = "video_" + System.currentTimeMillis();

            // 4. 设置上传状态
            videoCacheUtils.setProcessingStatus(videoId, "uploading", 0);

            // 模拟上传过程
            for (int i = 0; i <= 100; i += 20) {
                videoCacheUtils.setProcessingStatus(videoId, "uploading", i);
                try {
                    Thread.sleep(1000); // 模拟上传进度
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }

            // 5. 缓存视频信息
            Map<String, Object> videoInfo = new HashMap<>();
            videoInfo.put("videoId", videoId);
            videoInfo.put("fileName", filename);
            videoInfo.put("uploader", username);
            videoInfo.put("uploadTime", System.currentTimeMillis());
            videoInfo.put("title", filename.substring(0, filename.lastIndexOf(".")));
            videoCacheUtils.cacheVideoInfo(videoId, videoInfo);

            // 6. 添加到用户视频列表
            videoCacheUtils.addUserVideo(username, videoId);

            // 7. 添加到最近上传列表
            videoCacheUtils.addToRecentUploads(videoId);

            // 8. 更新处理状态为完成
            videoCacheUtils.setProcessingStatus(videoId, "completed", 100);

            System.out.println("视频上传成功: " + videoId);

        } finally {
            // 9. 释放锁
            redisLockUtils.unlock("video:upload:" + filename, lockValue);
        }
    }

    /**
     * 视频观看场景示例
     */
    public void videoViewScenario(String videoId, String userIp) {
        // 1. 观看限流检查
        if (!rateLimiterUtils.isVideoViewAllowed(userIp, 100, 3600)) {
            throw new RuntimeException("视频观看频率过高，请稍后再试");
        }

        // 2. 获取视频信息
        Map<Object, Object> videoInfo = videoCacheUtils.getVideoInfo(videoId);
        if (videoInfo == null || videoInfo.isEmpty()) {
            throw new RuntimeException("视频不存在");
        }

        // 3. 增加观看次数
        long viewCount = videoCacheUtils.incrementViewCount(videoId);

        // 4. 更新热度分数
        List<Object> tags = videoCacheUtils.getVideoTags(videoId);
        double hotScore = viewCount * 1.0 + tags.size() * 0.5;
        videoCacheUtils.addToHotVideos(videoId, hotScore);

        System.out.println("视频观看成功，当前观看次数: " + viewCount);
    }

    /**
     * 获取视频统计信息示例
     */
    public void getVideoStatistics(String username) {
        // 1. 获取用户视频数量
        long userVideoCount = videoCacheUtils.getUserVideoCount(username);
        System.out.println("用户 " + username + " 共上传了 " + userVideoCount + " 个视频");

        // 2. 获取用户的视频列表
        List<Object> userVideos = videoCacheUtils.getUserVideos(username);
        System.out.println("用户视频列表: " + userVideos);

        // 3. 获取最近上传的视频
        List<Object> recentVideos = videoCacheUtils.getRecentUploads(10);
        System.out.println("最近上传的10个视频: " + recentVideos);

        // 4. 获取热门视频
        List<Object> hotVideos = videoCacheUtils.getHotVideos(10);
        System.out.println("热门视频TOP10: " + hotVideos);

        // 5. 根据标签获取视频
        List<Object> techVideos = videoCacheUtils.getVideosByTag("技术");
        System.out.println("技术相关视频: " + techVideos);
    }

    /**
     * 视频处理状态监控示例
     */
    public void monitorVideoProcessing(String videoId) {
        Map<Object, Object> status = videoCacheUtils.getProcessingStatus(videoId);
        
        if (status != null && !status.isEmpty()) {
            String statusStr = (String) status.get("status");
            Integer progress = (Integer) status.get("progress");
            Long updateTime = (Long) status.get("updateTime");
            
            System.out.println("视频处理状态:");
            System.out.println("  状态: " + statusStr);
            System.out.println("  进度: " + progress + "%");
            System.out.println("  更新时间: " + new java.util.Date(updateTime));
        } else {
            System.out.println("视频处理状态不存在");
        }
    }
} 